# -*- coding: UTF-8 -*-

# Copyright (C) 2009 Daniele Favara.
# Written by Daniele Favara <daniele@zeroisp.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


import pylons
from sqlalchemy import *
from tg import expose, flash, require, url, request, redirect, validate, session
from tg.decorators import paginate
from pylons.i18n import ugettext as _, lazy_ugettext as l_
from repoze.what import predicates

from tw.api import *
from tw.forms import *

from tgext.zeroisp.lib.base import BaseController
from tgext.zeroisp.lib import utils
from tgext.zeroisp.lib import database
from tgext.zeroisp.model import DBSession, metadata

from tgext.zeroisp import model

from tgext.zeroisp.controllers.default import DefaultController
from formencode  import validators

from tgext.zeroisp.widgets import *

import logging

log = logging.getLogger(__name__)

__all__ = ['ToolboxController']


from tgext.zeroisp.widgets import *


add_field_form = FieldForm()

class KeywordController(DefaultController):

    @expose('tgext.zeroisp.templates.boxy')
    def add(self, team_alias, post_id, **kw):
        pylons.c.boxy =  KeywordForm(action=self.root_url+'/keyword/insert')
        return dict(value=dict(team_alias=team_alias, post_id=post_id),
                    root_url=self.root_url)

    @expose()
    def insert(self, **kw):
        database.insert_keyword(**kw)
        flash('Keyword Added !')
        return redirect(self.root_url+'/post/index/%s/%s'%(kw.get('team_alias'), kw.get('post_id')))

class CategoryController(DefaultController):

    @expose('tgext.zeroisp.templates.toolbox.tb-category')
    def index(self, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        categories = user= model.DBSession.query(model.Category).all()
        pylons.c.zeroisp_toolbox = zeroisp_toolbox
        pylons.c.zeroisp_boxy = zeroisp_boxy
        return dict(user=user,
                    categories=categories,
                    root_url=self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-category-show')
    def index(self, category_name, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        categories = user= model.DBSession.query(model.Category).filter_by(category_name=category_name).one()
        pylons.c.zeroisp_toolbox = zeroisp_toolbox
        pylons.c.zeroisp_boxy = zeroisp_boxy
        return dict(user=user,
                    category=category,
                    root_url=self.root_url)

    @expose('tgext.zeroisp.templates.boxy')
    def add(self, **kw):
        pylons.c.boxy =  CategoryForm(action=self.root_url+'/category/insert')
        return dict(value=dict(),
                    root_url=self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-category-add-field')
    def add_field(self, team_alias=None, category_id=None, **kw):
        user= DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        if team in user.teams:
            pylons.c.field_form = add_field_form
            pylons.c.zeroisp_toolbox = zeroisp_toolbox
            pylons.c.add_field = add_field_form
            value = {}
            value['team_alias'] = team_alias
            value['category_id'] = category_id
            return dict(value=value,
                        root_url=self.root_url)

    @expose('json')
    def insert(self, *args, **kw):
        database.insert_category(**kw)
        flash('Category Added !')
        return redirect(self.root_url+'')

    @validate(add_field_form, error_handler=add_field)
    @expose('json')
    def insert_field(self, *args, **kw):
        database.insert_field(**kw)
        flash('Posttype Added !')
        return redirect(self.root_url+'/team/index/%s'%(kw.get('team_alias')))


class PostController(DefaultController):
    """
    """

    @expose('tgext.zeroisp.templates.toolbox.tb-post')
    def index(self, team_alias, post_id, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        post = DBSession.query(model.Post).filter_by(post_id=int(post_id)).one()
        debug = kw.get('debug')
        if team in user.teams:
            if post in team.posts:
                pylons.c.pack = pack
                pylons.c.tabs = tabs
                pylons.c.googlemaps_js = self.googlemaps_js()
                pylons.c.zeroisp_fileupload  = Fileupload()
                teampage  = None
                if team.page:
                    if hasattr(team.page, 'post'):
                        if team.page.post:
                            teampage = team.page.post
                return dict(user=user,
                            team=team,
                            post = post,
                            debug = debug,
                            root_url=self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-post-sitemap')
    def sitemap(self, team_alias, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        if user in team.users:
            pylons.c.pack = pack
            posts = DBSession.query(model.Post).filter(
                                            and_(model.Post.post_parent==None,
                                                 model.Post.post_team_id==team.team_id)).all()
            return dict(team=team, posts=posts,
                        root_url=self.root_url)


    @expose('tgext.zeroisp.templates.toolbox.tb-post-select-category-boxy')
    def select_category_boxy(self, team_alias, parent_id='', **kw):
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        return dict(team=team,parent_id = parent_id, root_url=self.root_url)

    @expose('tgext.zeroisp.templates.boxy')
    def add(self, team_alias, post_category_id, post_parent='', **kw):
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        pylons.c.boxy = PostAddForm(action=self.root_url+'/post/insert')
        return dict(value=dict(team_alias=team_alias,
                               post_category_id=post_category_id,
                               post_parent=post_parent), root_url=self.root_url)

    @expose('tgext.zeroisp.templates.boxy')
    def edit(self, team_alias, post_id,  **kw):
        post = DBSession.query(model.Post).filter_by(post_id=post_id).one()
        pylons.c.boxy = PostEditForm(action=self.root_url+'/post/update')
        value = database.get_value(post, pylons.c.boxy)
        value['team_alias'] = team_alias
        value['post_id'] = post_id
        return dict(value=value,
                    root_url=self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-post-edit-content')
    def edit_content(self, team_alias, post_id, **kw):
        post = DBSession.query(model.Post).filter_by(post_id=post_id).one()
        pylons.c.pack = pack
        pylons.c.edit_post = PostEditContentForm(action=self.root_url+'/post/update')
        value = database.get_value(post, pylons.c.edit_post)
        value['team_alias'] = team_alias
        value['post_id'] = post_id
        return dict(value=value,root_url=self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-post-edit-address')
    def edit_address(self, team_alias, post_id, **kw):
        post = DBSession.query(model.Post).filter_by(post_id=post_id).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        pylons.c.pack = pack
        action = self.root_url + "/post/update_address/%s/%s"%(team.team_alias, post.post_id)
        pylons.c.zeroisp_toolbox = zeroisp_toolbox
        pylons.c.googlemaps_js = self.googlemaps_js()
        pylons.c.address_form = AddressForm(action=action)
        pylons.c.address_search_form = GmapSearchForm()
        pylons.c.gmap = ZeroispGmap(attrs=dict(style="min-width:300px; height:320px;"))
        value = database.get_value(post.post_address, pylons.c.address_form)
        return dict(value=value, post=post, team=team, root_url=self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-post-edit-details')
    def edit_details(self, team_alias, post_id, detail_id, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        post = DBSession.query(model.Post).filter_by(post_id=post_id).one()
        detail = DBSession.query(model.Detail).filter_by(detail_id=detail_id).one()
        pylons.c.pack = pack
        pylons.c.edit_details = DetailsForm(str(detail.detail_id),
        action = self.root_url + "/post/update_details/%s/%s/%s"%(team.team_alias,
                                                post.post_id, detail.detail_id))
        value={}
        for k,l,v in post.ordered_values(detail.detail_id):
            value[k] = v

        return dict(user=user, team=team, post = post, value=value, root_url=self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-post-edit-photo')
    def edit_photo(self, team_alias, post_id,photo_id, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        post = DBSession.query(model.Post).filter_by(post_id=post_id).one()
        if team in user.teams:
            if post.post_category in team.categories:
                pylons.c.pack = pack
                pylons.c.photo_form = PhotoForm(
                    action = self.root_url + "/post/update_photo/%s/%s"%(team.team_alias,post.post_id))
                album = self.picasa.get_album(str(post.post_album.album_id))
                value ={}
                for photo in album.entry:
                    if photo.gphoto_id.text == photo_id:
                        value['title'] = photo.title.text
                        value['summary'] = photo.summary.text
                        value['albumid'] = post.post_album.album_id
                        value['photoid']= photo.gphoto_id.text
                        break
                return dict(team=team,
                            value=value,
                            album=album,
                            photo=photo,
                            root_url=self.root_url)
    @expose()
    def insert(self, **kw):
        post_id = database.insert_post(**kw)
        return redirect(self.root_url+'/post/index/%s/%s'%(kw.get('team_alias'), post_id))

    @expose()
    def insert_child(self, **kw):
        team_alias = kw.get('team_alias')
        post_id = database.insert_post_child(**kw)
        return redirect(self.root_url+'/post/index/%s/%s'%(team_alias, post_id))

    @expose()
    def insert_album(self, team_alias, post_id, **kw):
        database.insert_album(team_alias, post_id, **kw)
        return redirect(self.root_url+'/post/index/%s/%s'%(team_alias, post_id))

    @expose()
    def insert_photos(self, team_alias, post_id, **kw):
        #print '='*10, kw , '='*10
        database.insert_photos(team_alias, post_id, **kw)
        return redirect(self.root_url+'/post/index/%s/%s'%(team_alias, post_id))

    @expose()
    def update_photo(self, team_alias, post_id, **kw):
        database.update_photo(team_alias, post_id, **kw)
        return redirect(self.root_url+'/post/index/%s/%s'%(team_alias, post_id))

    @expose()
    def update_details(self, team_alias, post_id, detail_id, **kw):
        database.update_details(team_alias, post_id, detail_id, **kw)
        return redirect(self.root_url+'/post/index/%s/%s'%(team_alias, post_id))


    @expose()
    def update_address(self, team_alias, post_id, **kw):
        database.update_post_address(team_alias, post_id, **kw)
        return redirect(self.root_url+'/post/index/%s/%s'%(team_alias, post_id))

    @expose()
    def update(self, **kw):
        database.update_post(**kw)
        return redirect(self.root_url+'/post/index/%s/%s'%(kw.get('team_alias'),
                                                     kw.get('post_id')))

class UserController(DefaultController):
    @expose('tgext.zeroisp.templates.toolbox.tb-user')
    def index(self, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        pylons.c.pack = pack
        pylons.c.change_password = PasswordEditForm(action=self.root_url + '/user/update_password')
        return dict(user=user,root_url=self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-user-all')
    def all(self, **kw):
        users= model.DBSession.query(model.User)
        pylons.c.pack = pack
        pylons.c.datatables = datatables
        return dict(users=users,root_url=self.root_url)

    @expose()
    def update_password(self, **kw):
        database.update_password(**kw)
        return redirect(self.root_url+'/user/')

class TeamController(DefaultController):
    @expose('tgext.zeroisp.templates.toolbox.tb-team')
    def index(self, team_alias, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        if team in user.teams:
            pylons.c.pack = pack
            pylons.c.tabs = tabs
            pylons.c.datatables = datatables
            pylons.c.googlemaps_js = self.googlemaps_js()
            teampage  = None
            if team.page:
                if hasattr(team.page, 'post'):
                    if team.page.post:
                        teampage = team.page.post
            return dict(user=user,
                        team=team, teampage=teampage,
                        root_url = self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-team-posts')
    def posts(self, team_alias, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        if team in user.teams:
            pylons.c.pack = pack
            pylons.c.tabs = tabs
            pylons.c.datatables = datatables
            pylons.c.googlemaps_js = self.googlemaps_js()
            teampage  = None
            if team.page:
                if hasattr(team.page, 'post'):
                    if team.page.post:
                        teampage = team.page.post
            return dict(user=user,
                        team=team, teampage=teampage,
                        root_url = self.root_url)

    @expose('tgext.zeroisp.templates.boxy')
    def add(self, **kw):
        pylons.c.pack = pack
        pylons.c.boxy = TeamForm(action=self.root_url+'/team/insert')
        return dict(value=dict(),
                    root_url = self.root_url)

    @expose('tgext.zeroisp.templates.boxy')
    def delete(self, team_alias, **kw):
        pylons.c.pack = pack
        pylons.c.boxy = TeamForm(action=self.root_url+'/team/insert')
        return dict(value=dict(),
                    root_url = self.root_url)

    @expose('tgext.zeroisp.templates.boxy')
    def add_page(self, team_alias, **kw):
        pylons.c.pack = pack
        pylons.c.boxy = PostAddForm(action=self.root_url+'/team/insert_page')
        return dict(value=dict(team_alias=team_alias),
                    root_url = self.root_url)

    @expose('tgext.zeroisp.templates.boxy')
    def edit_page(self, team_alias, **kw):
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        pylons.c.pack = pack
        pylons.c.boxy = PostAddForm(action=self.root_url+'/team/update_page')
        value=database.get_value(team.page, pylons.c.boxy)
        value['team_alias'] = team_alias
        return dict(value=value,
                    root_url = self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-team-edit-page-content')
    def edit_page_content(self, team_alias, **kw):
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        pylons.c.pack = pack
        pylons.c.boxy = PostContentAddForm(action=self.root_url+'/team/update_page')
        value = database.get_value(team.page, pylons.c.boxy)
        value['team_alias'] = team_alias
        return dict(value=value,
                    root_url = self.root_url)

    @expose('tgext.zeroisp.templates.toolbox.tb-team-edit-page-address')
    def edit_page_address(self, team_alias, **kw):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        team = DBSession.query(model.Team).filter_by(team_alias=team_alias).one()
        pylons.c.pack = pack
        pylons.c.googlemaps_js = self.googlemaps_js()
        pylons.c.address_form = AddressForm(
                                    action=self.root_url+'/team/update_address/%s'%(
                                                            team.team_alias))
        pylons.c.address_search_form = GmapSearchForm()
        pylons.c.gmap = Gmap(attrs=dict(style="min-width:300px; height:320px;"))
        value = database.get_value(team.address, pylons.c.address_form)
        return dict(user=user, team=team, value=value, root_url = self.root_url)

    @expose()
    def insert(self,  **kw):
        database.insert_team(**kw)
        return redirect(self.root_url+'/team/index/%s'%(kw.get('team_alias')))

    @expose()
    def insert_page(self, **kw):
        database.insert_teampage(**kw)
        return redirect(self.root_url+'/team/index/%s'%(kw.get('team_alias')))

    @expose()
    def update_page(self, **kw):
        database.update_teampage(**kw)
        return redirect(self.root_url+'/team/index/%s'%(kw.get('team_alias')))

    @expose()
    def update_address(self, team_alias, **kw):
        database.update_teamaddress(team_alias, **kw)
        return redirect(self.root_url+'/team/index/%s'%(team_alias))


class ExportController(BaseController):

    @expose('tgext.zeroisp.templates.export_addresses')
    def address(self):
        teams= model.DBSession.query(model.Team).all()
        return dict(teams=teams)

class ToolboxController(DefaultController):
    allow_only = predicates.not_anonymous()
    export = ExportController()

    @expose('tgext.zeroisp.templates.toolbox.tb-index')
    def index(self):
        user= model.DBSession.query(model.User).filter_by(user_name=request.identity['repoze.who.userid']).one()
        pylons.c.pack = pack
        pylons.c.datatables = datatables
        return dict(page="index",
                    user=user,
                    root_url = self.root_url
                    )

